package com.itdev.matcherapp.android;

import java.util.List;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentReceiver;
import android.content.ServiceConnection;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.DeadObjectException;
import android.os.IBinder;
import android.widget.Toast;

import com.google.android.gtalkservice.IGTalkService;
import com.google.android.gtalkservice.IGTalkSession;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayController;
import com.google.android.maps.Point;
import com.itdev.matcherapp.android.fakeservice.PeopleLocationBean;
import com.itdev.matcherapp.android.fakeservice.ServiceFaky;

public class Map extends MapActivity {
	public static final String ACTION_LOCATION_CHANGE = "com.itdev.matcherapp.android.ACTION_LOCATION_CHANGE";
	public static boolean canUpdate = true;
	private static final float MINIMUM_LOCATION_CHANGE_UPDATE = 30.0f;
	private static final int MINIMUM_TIME_UPDATE = 10000;
	public static IGTalkSession mGTalkSession;
	private Intent intentLocationChange = new Intent(ACTION_LOCATION_CHANGE);
	private IntentFilter intentFillter = new IntentFilter(
			Map.ACTION_LOCATION_CHANGE);
	private IntentFilter intentFilterTest = new IntentFilter(
			PeopleMatchingList.ACTION_MATCHING_LIST_CHANGE);
	// private IntentFilter intentFillter = new
	// IntentFilter(PeopleFillterService.ACTION_LOCATION_CHANGE_PROCESSING);
	private IntentReceiverLocationChange intentReceiverLocationChange = new IntentReceiverLocationChange();
	private LocationManager myLocationManager;
	private LocationProvider locationProvider;
	private MapView myMapView;
	protected MapController myMapController;
	private MapOverlay mapOverlay = new MapOverlay();
	private OverlayController myOverlayController;
	private int latitude;
	private int longitude;
	static {
		ServiceFaky.initInstance();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		//unregisterReceiver(intentReceiverLocationChange);
	}

	@Override
	protected void onPause() {
		try{
			unregisterReceiver(intentReceiverLocationChange);
		} catch(Exception ex){
			
		}
		super.onPause();
		//unregisterReceiver(intentReceiverLocationChange);
	}

	@Override
	protected void onResume() {
		registerReceiver(intentReceiverLocationChange, intentFillter);
		super.onResume();
		//registerReceiver(intentReceiverLocationChange, intentFillter);
	}

	@Override
	protected void onStop() {
		try{
			unregisterReceiver(intentReceiverLocationChange);
		}catch(Exception ex){
			
		}
		super.onStop();
		//unregisterReceiver(intentReceiverLocationChange);
	}

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		bindService(
				(new Intent())
						.setComponent(com.google.android.gtalkservice.GTalkServiceConstants.GTALK_SERVICE_COMPONENT),
				mConnection, 0);
		myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationProvider = myLocationManager.getProvider("test1");
		myMapView = new MapView(this);
		setContentView(myMapView);
		myMapController = this.myMapView.getController();
		myOverlayController = myMapView.createOverlayController();
		myOverlayController.add(mapOverlay, true);
		myMapController.zoomTo(18);
		Location curLocation = myLocationManager
				.getCurrentLocation(locationProvider.getName());
		latitude = (int) (curLocation.getLatitude() * 1E6);
		longitude = (int) (curLocation.getLongitude() * 1E6);
		// myLocationManager.requestUpdates(locationProvider,
		// MINIMUM_TIME_UPDATE,
		// MINIMUM_LOCATION_CHANGE_UPDATE, intentLocationChange);
		myMapController.animateTo(new Point(latitude, longitude));
		registerReceiver(intentReceiverLocationChange, intentFillter);
		//registerReceiver(intentReceiverLocationChange, intentFilterTest);
	}

	public void updateLocation(Point pointLocation,
			List<PeopleLocationBean> pList) {
		latitude = pointLocation.getLatitudeE6();
		longitude = pointLocation.getLongitudeE6();
		mapOverlay.setPeopleDatas(pList);
		myMapView.postInvalidate();
		myMapController.centerMapTo(new Point(latitude, longitude), true);
	}

	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
			// This is called when the connection with the GTalkService has been
			// established, giving us the service object we can use to
			// interact with the service. We are communicating with our
			// service through an IDL interface, so get a client-side
			// representation of that from the raw service object.
			IGTalkService GTalkService = IGTalkService.Stub
					.asInterface(service);

			try {
				mGTalkSession = GTalkService.getDefaultSession();

				if (mGTalkSession == null) {
					// this should not happen.
					return;
				}
			} catch (DeadObjectException ex) {
				// showMessage("Session not found");
			}

		}

		public void onServiceDisconnected(ComponentName className) {
			mGTalkSession = null;
		}
	};
}

class IntentReceiverLocationChange extends IntentReceiver {

	@Override
	public void onReceiveIntent(Context context, Intent intent) {
		Map.canUpdate = false;
		if (intent.getAction().equals(Map.ACTION_LOCATION_CHANGE)) {
			Location curLoc = (Location) intent.getExtra("location");
			int lat = (int) (curLoc.getLatitude() * 1E6);
			int lng = (int) (curLoc.getLongitude() * 1E6);
			List<PeopleLocationBean> pList = (List<PeopleLocationBean>) intent
					.getSerializableExtra("peoplelist");
//			Toast.makeText(
//					context,
//					"receive intent: " + Integer.toString(lat) + ", "
//							+ Integer.toString(lng)+" Count:"+PeopleFillterService.notUpdate, Toast.LENGTH_SHORT).show();
			((Map) context).updateLocation(new Point(lat, lng), pList);
		}
		Map.canUpdate = true;
	}

}

class MapOverlay extends Overlay {
	private List<PeopleLocationBean> peopleList;

	@Override
	public void draw(Canvas canvas, PixelCalculator calculator, boolean shadow) {
		super.draw(canvas, calculator, shadow);
		Paint paint = new Paint();
		paint.setStyle(Style.FILL);
		paint.setARGB(150, 0, 0, 255);
		try {
			if (Map.mGTalkSession != null) {
				for (PeopleLocationBean people : peopleList) {
					int xy[] = new int[2];
					Point point = new Point(people.getLatitude(), people
							.getLongitude());
					calculator.getPointXY(point, xy);
					paint.setARGB(150, 0, 0, 255);
					canvas.drawCircle(xy[0], xy[1], 10, paint);
					paint.setARGB(255, 0, 0, 0);
					canvas.drawText(people.getGmailAccount(), xy[0], xy[1],
							paint);
					// canvas.drawText(Long.toString(point.getLatitudeE6())+",
					// "+Long.toString(point.getLongitudeE6()), 100, 300,
					// paint);
				}
				// canvas.drawText(Integer.toString(peopleList.size()), 200,
				// 200, paint);
			} else {
				canvas.drawText("NULL", 200, 200, paint);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void setPeopleDatas(List<PeopleLocationBean> peopleList) {
		this.peopleList = peopleList;
	}
}
